import React, { Component, Fragment } from 'react';
import { Modal, Badge, Tooltip, Collapse, message } from 'antd';
import { MessageOutlined, DownOutlined } from '@ant-design/icons';
import axios from './../../axios';
import Utils from './../../utils/utils';
import { getCookie } from './../../utils/common';
import './index.less';

const { Panel } = Collapse;

let ws = null;
let pageSize = 1;

class ReactWebsocket extends Component {
	
	formRef = React.createRef();
	
	state={
		isReadVisible: false,
		isWriteVisible: false,
		count: 0,//未读消息数量
		noticeMenu: [],//未读消息
		isLoadingMore: "点击加载更多"
	}
	
	//遍历消息
	renderNoticeMenu = data => {
		return data && data.map(val => {
			return <Panel 
				header={val.title}
				key={val._id} 
				className="site-collapse-custom-panel"
			>
				<p>消息内容:{val.content}</p>
				<p>发布者:{val.user.user_name}&nbsp;&nbsp;发布时间:{Utils.formateDate(val.create_time)}</p>
			</Panel>
		})
	}
	
	//用户公告查询
	requestList = (page = 1) => {
		axios.ajax({
			url: "/User/Notice/noticeRetrieveByUnread", 
			method: "post",
			data: {page: page, limit: "10"},
		}).then(res=>{
			if(res.code === 0){
				if(res.result && res.result.data){
					let data = res.result.data;
					if(data && data.length > 0){
						//遍历有多少个未读消息
						let count = 0;
						for(let val of data){
							if(val.read.is_read === 0){
								count ++;
							}
						}
						let noticeMenuBefore = this.state.noticeMenu;
						let noticeMenu = this.renderNoticeMenu(data);
						this.setState({count,noticeMenu:noticeMenuBefore.concat(noticeMenu)});
					}else{
						this.setState({isLoadingMore: "没有更多了"});
					}
				}
			}
		})
	}
	
	//展开消息,并标记已读
	onChange = key => {
		//如果key有值	
		if(key && key !== "undefined"){
			axios.ajax({
				url: "/User/Notice/noticeConfirm", 
				method: "post",
				data: {id: key}
			}).then(res=>{
				if(res.code === 0){
				}
			})
		}
	}
	
	handleRead = () => {
		this.setState({
			isReadVisible: true
		});
	}
	
	//加载更多
	loadMore = () => {
		this.requestList(pageSize + 1);
	}
	
	hasNewSocket = () => {
		let cookie = getCookie("jqmkj_ss");
		if(!cookie)return;
		ws = new WebSocket("ws://192.168.188.209:9501", cookie);	
		//重试创建socket连接
		try {
			ws.connection();
		} catch (e) {
			//捕获异常
		}
		//连接
		ws.onopen = function(){
			// console.log("连接成功");
		}
		
		// 关闭 websocket
		ws.onclose = function(){ 
		  // console.log("连接已关闭"); 
		}
		//接收数据
		let _this = this;
		ws.onmessage = function(evt){
			// console.log(evt.data);
			message.info("您有最新的消息，请及时查看");
			_this.requestList();
		}
	}
	
	componentDidMount(){
		const login = document.cookie.includes('login=true');
		const pathname = window.location.pathname;
		if(login && pathname.indexOf("login") === -1){
			this.requestList();
			this.hasNewSocket();
		}
	}
	
	componentWillUnmount(){
		//关闭socket
		if(ws){
			ws.close();
		}
	}
	
	render(){
		return (
			<Fragment>
				<div onClick={this.handleRead} className="message-wrap">
					<Tooltip placement="bottom" title={`${this.state.count}条未读`}>
						<MessageOutlined className="message-img" />
					</Tooltip>
					<Badge count={this.state.count} offset={[10, -30]} />	
				</div>
				<Modal
					title="消息通知"
					visible={this.state.isReadVisible}
					onCancel={()=>this.setState({isReadVisible: false})}
					footer={null}
					className="notice-modal"
				>
					{
						this.state.count > 0 ?
						<>
							<Collapse 
								accordion 
								bordered={false} 
								ghost 
								onChange={this.onChange}
								className="site-collapse-custom-collapse"
							>
								{this.state.noticeMenu}
							</Collapse>
							<div onClick={this.loadMore} className="loading-more">{this.state.isLoadingMore}<DownOutlined /></div>
						</>
						:
						<p style={{textAlign: "center"}}>暂无消息</p>
					}
					
				</Modal>
			</Fragment>
		)
	}
}

export default ReactWebsocket;